﻿
//
// Group Item: An item which is a combination of other items.
//  Once a group item get sold, the stock of all sub items should be decreased.
//
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace EbayMaster
{
    public partial class FrmGroupItem : Form
    {
        public String ItemSKU = null;
        public List<ItemCompactInfo> selectedSubItems = new List<ItemCompactInfo>();

        double computeSubItemsTotalCost()
        {
            double totalCost = 0.0;
            foreach (ItemCompactInfo item in selectedSubItems)
            {
                totalCost += item.ItemCost;
            }

            return totalCost;
        }

        double computeSubItemsTotalWeight()
        {
            double totalWeight = 0.0;
            foreach (ItemCompactInfo item in selectedSubItems)
            {
                totalWeight += item.ItemWeight;
            }

            return totalWeight;
        }

        string computeSubItemsSKUString()
        {
            string skustr = "";
            bool first = true;
            foreach (ItemCompactInfo item in selectedSubItems)
            {
                if (!first)
                    skustr += "-";
                else
                    first = false;

                skustr += item.ItemSKU;
            }

            return skustr;
        }

        public FrmGroupItem()
        {
            InitializeComponent();
        }

        private void ShowItemWithSKU(String itemSKU)
        {
            DataTable dtItem = ItemDAL.GetItemTableBySKU(itemSKU);
            TreeNode[] nodes = this.treeViewCategories.Nodes.Find(itemSKU, true);
            if (nodes.Length == 0)
                return;

            this.treeViewCategories.SelectedNode = nodes[0];
        }

        private void FrmGroupItem_Load(object sender, EventArgs e)
        {
            LoadAllCategories();
            LoadAllItems();

            if (ItemSKU != null && ItemSKU != "")
            {
                ShowItemWithSKU(ItemSKU);
                this.treeViewCategories.Enabled = false;
            }

            //this.listViewSubItems.View = View.List;
        }

        public class ItemCompactInfo
        {
            public int ItemId;
            public int CategoryId;
            public string ItemName;
            public string ItemSKU;
            public int ItemStock;
            public double ItemCost;
            public double ItemWeight;
            public bool IsGroupItem;

            public ItemCompactInfo(int itemId, int catId, string itemName, string itemSKU, int itemStock, double itemCost, double itemWeight, bool isGroupItem)
            {
                this.ItemId = itemId;
                this.CategoryId = catId;
                this.ItemName = itemName;
                this.ItemSKU = itemSKU;
                this.ItemStock = itemStock;
                this.ItemCost = itemCost;
                this.ItemWeight = itemWeight;
                this.IsGroupItem = isGroupItem;
            }
        }   // class ItemCompactInfo

        private void LoadAllItems()
        {
            DataTable dtItems = ItemDAL.GetAllItems();
            if (dtItems.Rows.Count == 0)
                return;

            foreach (DataRow dr in dtItems.Rows)
            {
                int itemId = StringUtil.GetSafeInt(dr["ItemId"]);
                int itemCatId = StringUtil.GetSafeInt(dr["CategoryId"]);
                string itemName = StringUtil.GetSafeString(dr["ItemName"]);
                string itemSKU = StringUtil.GetSafeString(dr["ItemSKU"]);
                int itemStock = StringUtil.GetSafeInt(dr["ItemStockNum"]);
                double itemCost = StringUtil.GetSafeDouble(dr["ItemCost"]);
                double itemWeight = StringUtil.GetSafeDouble(dr["ItemWeight"]);
                bool isGroupItem = StringUtil.GetSafeBool(dr["IsGroupItem"]);

                ItemCompactInfo itemInfo = new ItemCompactInfo(itemId, itemCatId, itemName, itemSKU, itemStock, itemCost, itemWeight, isGroupItem);
                TreeNode itemNode = new TreeNode();
                itemNode.Text = string.Format("[{0}] {1}", itemSKU, itemName);
                itemNode.Tag = itemInfo;
                itemNode.Name = itemSKU;

                // Add this item to corresponding category subtree.
                TreeNode[] nodes = this.treeViewCategories.Nodes.Find(itemCatId.ToString(), true);
                if (nodes.Length == 1)
                {
                    nodes[0].Nodes.Add(itemNode);
                }
            } // Iterate over all items
        }   // LoadAllItems

        private void LoadAllCategories()
        {
            DataTable dtCategories = CategoryDAL.GetAllCategories();
            if (dtCategories.Rows.Count == 0)
                return;

            this.treeViewCategories.Nodes.Clear();

            foreach (DataRow dr in dtCategories.Rows)
            {
                int catId = StringUtil.GetSafeInt(dr["CategoryId"]);
                int parentCatId = StringUtil.GetSafeInt(dr["ParentCategoryId"]);
                string catName = StringUtil.GetSafeString(dr["CategoryName"]);

                CategoryType catType = new CategoryType();
                catType.CategoryId = catId;
                catType.ParentCategoryId = parentCatId;
                catType.CategoryName = catName;

                TreeNode newNode = new TreeNode();
                newNode.Tag = catType;
                newNode.Text = catName;
                newNode.Name = catId.ToString();

                if (parentCatId == -1)
                {
                    this.treeViewCategories.Nodes.Add(newNode);
                }
                else
                {
                    TreeNode[] parentNodes = this.treeViewCategories.Nodes.Find(parentCatId.ToString(), true);
                    if (parentNodes.Length == 1)
                        parentNodes[0].Nodes.Add(newNode);
                }
            }

            this.treeViewCategories.ExpandAll();
            return;
        }   // LoadAllCategories


        private void loadChecked(TreeNodeCollection tNodeList, List<ItemCompactInfo> checkedItems)
        {
            foreach (TreeNode tNode in tNodeList)
            {
                if (tNode.Checked)
                {
                    // Only load items, not categories.
                    if (tNode.Tag.GetType() == typeof(ItemCompactInfo))
                    {
                        ItemCompactInfo itemInfo = (ItemCompactInfo)(tNode.Tag);
                        if (itemInfo == null)
                            continue;

                        checkedItems.Add(itemInfo);
                    }
                }
                loadChecked(tNode.Nodes, checkedItems);
            }
        }

        public Image ResizeImg(Image img, int width, int height)
        {
            //create a new Bitmap the size of the new image
            Bitmap bmp = new Bitmap(width, height);
            //create a new graphic from the Bitmap
            Graphics graphic = Graphics.FromImage((Image)bmp);
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //draw the newly resized image
            graphic.DrawImage(img, 0, 0, width, height);
            //dispose and free up the resources
            graphic.Dispose();
            //return the image
            return (Image)bmp;
        }

        private void updateSubItemsListView()
        {
            this.listViewSubItems.Items.Clear();

            ImageList subItemImages = new ImageList();

            foreach (ItemCompactInfo itemInfo in selectedSubItems)
            {
                int itemId = itemInfo.ItemId;
                string itemSKU = itemInfo.ItemSKU;

                DataTable dtItem = ItemDAL.GetItemTableById(itemId);

                if (dtItem.Rows.Count == 0)
                    return;

                DataRow dr = dtItem.Rows[0];

                //byte[] buffer = dr["ItemImage"] as byte[];
                String imgPath = StringUtil.GetSafeString(dr["ItemImagePath"]);
                bool foundImg = false;
                if (imgPath != null && File.Exists(imgPath))
                {
                    foundImg = true;
                }

                if (!foundImg)
                {
                    imgPath = "noimg.jpg";
                }

                Image rawImage = Image.FromFile(imgPath);

                int imageSize = 48;
                Image image = ResizeImg(rawImage, imageSize, imageSize);

                subItemImages.ImageSize = new System.Drawing.Size(imageSize, imageSize);
                subItemImages.Images.Add(image);

            }

            this.listViewSubItems.LargeImageList = subItemImages;

            for (int i = 0; i < subItemImages.Images.Count; i++)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.ImageIndex = i;
                lvi.Text = selectedSubItems[i].ItemName;
                lvi.ToolTipText = selectedSubItems[i].ItemName;
                this.listViewSubItems.Items.Add(lvi);
            }

        }

        private void updateGroupItemInfo()
        {
            int stock = 10000;
            foreach (ItemCompactInfo item in this.selectedSubItems)
            {
                if (item.ItemStock < stock)
                    stock = item.ItemStock;
            }

            this.textBoxGroupItemAvailableStock.Text = stock.ToString();
        }

        private void treeViewCategories_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
            {

                //Event call by mouse or key-press

                SetNodeCheckStatus(e.Node, e.Node.Checked);

                this.selectedSubItems.Clear();
                loadChecked(this.treeViewCategories.Nodes, this.selectedSubItems);

                updateSubItemsListView();

                updateGroupItemInfo();
            }
        }

        private void SetNodeCheckStatus(TreeNode tn, bool Checked)
        {

            if (tn == null) return;

            // Check children nodes

            foreach (TreeNode tnChild in tn.Nodes)
            {
                tnChild.Checked = Checked;
                SetNodeCheckStatus(tnChild, Checked);
            }

            // Set parent check status

            TreeNode tnParent = tn;

            int nNodeCount = 0;

            while (tnParent.Parent != null)
            {

                tnParent = (TreeNode)(tnParent.Parent);

                nNodeCount = 0;

                foreach (TreeNode tnTemp in tnParent.Nodes)

                    if (tnTemp.Checked == Checked)

                        nNodeCount++;

                if (nNodeCount == tnParent.Nodes.Count)

                    tnParent.Checked = Checked;

                else

                    tnParent.Checked = false;

            }

        }

        private void textBoxCustomName_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBoxItemCustomWeight_TextChanged(object sender, EventArgs e)
        {

        }

        private void buttonNavigateItemImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "图片文件(*.jpg,*.gif,*.bmp)|*.jpg;*.gif;*.bmp ";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filePath = dlg.FileName;
                this.textBoxItemImagePath.Text = filePath;
                Image image = Image.FromFile(filePath);
                Image resizedImage = ResizeImg(image, this.pictureBoxItemPic.Width, this.pictureBoxItemPic.Height);

                this.pictureBoxItemPic.Image = resizedImage;

            }
        }

        private void buttonAddNewItem_Click(object sender, EventArgs e)
        {
            InventoryItemType item = new InventoryItemType();

            TreeNode node = this.treeViewCategories.SelectedNode;
            if (node == null)
            {
                MessageBox.Show("请选择商品类别");
                return;
            }

            if (node.Tag.GetType() != typeof(CategoryType))
            {
                MessageBox.Show("请选择商品类别");
                return;
            }

            CategoryType category = (CategoryType)node.Tag;
            if (category == null)
            {
                MessageBox.Show("请选择商品类别");
                return;
            }

            item.CategoryId = category.CategoryId;
            if (item.CategoryId <= 0)
            {
                MessageBox.Show("请选择商品类别");
                return;
            }

            item.ItemName = this.textBoxItemName.Text;
            if (item.ItemName == "")
            {
                MessageBox.Show("请输入商品名");
                return;
            }

            item.ItemSKU = this.textBoxItemSKU.Text;
            if (item.ItemSKU == "")
            {
                MessageBox.Show("请输入商品SKU");
                return;
            }

            if (this.textBoxItemImagePath.Text == "")
            {
                MessageBox.Show("请选择商品图片");
                return;
            }

            string imagePath = this.textBoxItemImagePath.Text.Trim();
            if (File.Exists(imagePath) == false)
            {
                MessageBox.Show("商品图片路径错误.");
                return;
            }

            item.ItemImagePath = imagePath;

            item.ItemStockShresholdNum = 1000;
            item.ItemStockNum = 1000;
            item.ItemSourcingInfo = "";
            item.ItemWeight = 0.0;
            item.ItemCost = 0.0;

            //if (this.textBoxItemStockShreshold.Text == "")
            //{
            //    MessageBox.Show("商品库存警戒值错误");
            //    return;
            //}

            //item.ItemStockShresholdNum = Int32.Parse(this.textBoxItemStockShreshold.Text.Trim());

            //string itemStockStr = this.textBoxItemStock.Text;
            //if (itemStockStr.Trim() == "")
            //{
            //    MessageBox.Show("商品库存值错误");
            //    return;
            //}
            //item.ItemStockNum = Int32.Parse(itemStockStr);

            //item.ItemSourcingInfo = this.textBoxItemSourcingInfo.Text;

            //string itemCostStr = this.textBoxItemCost.Text.Trim();
            //if (itemCostStr == "")
            //{
            //    MessageBox.Show("商品成本值错误");
            //    return;
            //}
            //item.ItemCost = Double.Parse(itemCostStr);

            //string itemWeightStr = this.textBoxItemWeight.Text.Trim();
            //if (itemWeightStr == "")
            //{
            //    MessageBox.Show("商品重量值错误");
            //    return;
            //}
            //item.ItemWeight = Double.Parse(itemWeightStr);

            item.ItemCustomName = this.textBoxCustomName.Text.Trim();

            string itemCustomWeightStr = this.textBoxItemCustomWeight.Text.Trim();
            if (itemCustomWeightStr == "")
                item.ItemCustomWeight = 0.0;
            else
                item.ItemCustomWeight = Double.Parse(itemCustomWeightStr);

            string itemCustomCostStr = this.textBoxItemCustomValue.Text.Trim();
            if (itemCustomCostStr == "")
                item.ItemCustomCost = 0.0;
            else
                item.ItemCustomCost = Double.Parse(itemCustomCostStr);

            item.ItemAddDateTime = DateTime.Now;

            // IsGroupItem
            item.IsGroupItem = true;
            if (item.IsGroupItem)
            {
                string subItemSKUs = computeSubItemsSKUString();
                item.SubItemSKUs = subItemSKUs;
            }

            int newItemId = ItemDAL.InsertOneItem(item);

            // Add this item to tree view.
            TreeNode[] nodes = this.treeViewCategories.Nodes.Find(item.CategoryId.ToString(), true);
            if (nodes.Length == 1)
            {
                TreeNode newNode = new TreeNode();
                newNode.Text = item.ItemName;

                double totalCost = computeSubItemsTotalCost();
                double totalWeight = computeSubItemsTotalWeight();

                int stock = 10000;
                foreach (ItemCompactInfo itemInfo in this.selectedSubItems)
                {
                    if (itemInfo.ItemStock < stock)
                        stock = itemInfo.ItemStock;
                }

                ItemCompactInfo newItemInfo = new ItemCompactInfo(newItemId, item.CategoryId, item.ItemName, item.ItemSKU, stock, totalCost, totalWeight, true);
                newNode.Tag = newItemInfo;
                nodes[0].Nodes.Add(newNode);
            }
        }

        private void treeViewCategories_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = this.treeViewCategories.SelectedNode;
            if (node.Tag == null)
                return;

            if (node.Tag.GetType() != typeof(ItemCompactInfo))
            {
                //this.selectedSubItems.Clear();
                //updateSubItemsListView();
                return;
            }

            ItemCompactInfo itemInfo = (ItemCompactInfo)(node.Tag);
            if (itemInfo == null)
                return;

            if (itemInfo.IsGroupItem == false)
            {
               // this.selectedSubItems.Clear();
                //updateSubItemsListView();
                return;
            }

            int itemId = itemInfo.ItemId;
            DataTable dtItem = ItemDAL.GetItemTableById(itemId);

            if (dtItem.Rows.Count == 0)
                return;

            DataRow dr = dtItem.Rows[0];

            string skustr = dr["SubItemSKUs"].ToString();

            this.textBoxItemName.Text = dr["ItemName"].ToString();
            this.textBoxItemSKU.Text = dr["ItemSKU"].ToString();
            //this.textBoxItemStockShreshold.Text = dr["ItemStockShresholdNum"].ToString();
            //this.textBoxItemStock.Text = dr["ItemStockNum"].ToString();
           // this.textBoxItemSourcingInfo.Text = dr["ItemSourcingInfo"].ToString();
           // this.textBoxItemCost.Text = dr["ItemCost"].ToString();
           // this.textBoxItemWeight.Text = dr["ItemWeight"].ToString();
            this.textBoxCustomName.Text = dr["ItemCustomName"].ToString();
            this.textBoxItemCustomWeight.Text = dr["ItemCustomWeight"].ToString();
            this.textBoxItemCustomValue.Text = dr["ItemCustomCost"].ToString();


            byte[] buffer = dr["ItemImage"] as byte[];
            MemoryStream ms = new MemoryStream(buffer);
            Image rawImage = Image.FromStream(ms);
            int width = this.pictureBoxItemPic.Width;
            int height = this.pictureBoxItemPic.Height;
            Image image = ResizeImg(rawImage, width, height);
            this.pictureBoxItemPic.Image = image;

            this.selectedSubItems.Clear();
            string[] skuArr = skustr.Split(new char[] { '-' });
            foreach (string sku in skuArr)
            {
                if (sku == "")
                    continue;
                InventoryItemType item = ItemDAL.GetItemBySKU(sku);
                if (item == null)
                    continue;
                ItemCompactInfo itemInfoLoc = new ItemCompactInfo(item.ItemId, item.CategoryId, item.ItemName, item.ItemSKU,
                    item.ItemStockNum, item.ItemCost, item.ItemWeight, item.IsGroupItem);
                this.selectedSubItems.Add(itemInfoLoc);
            }
            updateSubItemsListView();
        }   // treeViewCategories_AfterSelect

    }
}
